package com.wex.cookbook.controller;

import com.wex.cookbook.utils.SuperVerifyCode;
import com.wex.cookbook.utils.Verification;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.Duration;

/**
 * @author wex
 * 2023/8/4
 */

@Api(value = "验证码")
@RestController
@RequestMapping("/verifyCode")
public class VerificationCodeController {

    private final RedisTemplate<String, String> redisTemplate;

    public VerificationCodeController(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @ApiOperation(value = "获取验证码")
    @GetMapping
    public ResponseEntity<byte[]> showCode(HttpSession httpSession){
        Verification verification = SuperVerifyCode.generateRandomSumImg();
        if(verification != null) {
            //将验证码存入redis,10分钟过期
            redisTemplate.opsForValue().set("_code", verification.getCode(), Duration.ofMinutes(10));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<>(verification.getBuffer(),headers, HttpStatus.OK);
        }
        return null;
    }
}
